package com.rainbow.bam.service.shiro;

import java.io.Serializable;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import com.google.common.base.Objects;
import com.rainbow.bam.BaseService;
import com.rainbow.bam.entity.HtAccount;
import com.rainbow.bam.service.account.HtAccountService;
import com.rainbow.bam.util.Encodes;

/**
 * shiro认证授权realm实现类
 * 
 * @author zhaolei
 * @version $Id: ShiroDbRealm.java, v 0.1 2015年11月11日 下午4:31:31 zhaolei Exp $
 */
public class ShiroDbRealm extends AuthorizingRealm {

    @Lazy //延迟到第一次使用时候注入
    @Autowired
    private HtAccountService accountService;
    
    @Lazy
    @Autowired
    private BaseService baseService;

    /**
     * 认证回调函数,登录时调用.
     * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        HtAccount user = accountService.findByAccountName(token.getUsername());
        if (user != null) {
            if (Boolean.TRUE.equals(user.getLocked())) {
                throw new LockedAccountException(); //帐号锁定
            }
            byte[] salt = Encodes.decodeHex(user.getSalt());
            return new SimpleAuthenticationInfo(
                new ShiroUser(user.getId(), user.getAccountName(), user.getUserName()),
                user.getPassword(), ByteSource.Util.bytes(salt), getName());
        } else {
            return null;
        }
    }

    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
     * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(baseService.findRoles(shiroUser.acctName));
        authorizationInfo.setStringPermissions(baseService.findPermissions(shiroUser.acctName));
        return authorizationInfo;
    }
    /**
     * 自定义Authentication对象，使得Subject除了携带用户的登录名外还可以携带更多信息.
     * @author zhaolei
     * @version $Id: ShiroDbRealm.java, v 0.1 2015年11月11日 下午4:32:40 zhaolei Exp $
     */
    public static class ShiroUser implements Serializable {
        private static final long serialVersionUID = -1373760761780840081L;
        public Long               id;
        public String             acctName;
        public String             userName;

        public ShiroUser(Long id, String acctName, String userName) {
            this.id = id;
            this.acctName = acctName;
            this.userName = userName;
        }

        public String getAcctName() {
            return acctName;
        }

        public void setAcctName(String acctName) {
            this.acctName = acctName;
        }

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        /**
         * 本函数输出将作为默认的<shiro:principal/>输出.
         */
        @Override
        public String toString() {
            return acctName;
        }

        /**
         * 重载hashCode,只计算acctName;
         */
        @Override
        public int hashCode() {
            return Objects.hashCode(acctName);
        }

        /**
         * 重载equals,只计算acctName;
         */
        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            ShiroUser other = (ShiroUser) obj;
            if (acctName == null) {
                if (other.acctName != null) {
                    return false;
                }
            } else if (!acctName.equals(other.acctName)) {
                return false;
            }
            return true;
        }
    }

    @Override
    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }

    @Override
    public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
        super.clearCachedAuthenticationInfo(principals);
    }

    @Override
    public void clearCache(PrincipalCollection principals) {
        super.clearCache(principals);
    }

    public void clearAllCachedAuthorizationInfo() {
        getAuthorizationCache().clear();
    }

    public void clearAllCachedAuthenticationInfo() {
        getAuthenticationCache().clear();
    }

    public void clearAllCache() {
        clearAllCachedAuthenticationInfo();
        clearAllCachedAuthorizationInfo();
    }
}
